﻿<!DOCTYPE html>
<html>
<head> 
	<!--<script type="text/javascript" src="getselection.js"></script>-->
	<script type="text/javascript" src="http://www.google.com/jsapi"></script>
	<script type="text/javascript" src="js/chrome_ex_oauthsimple.js"></script>
    <script type="text/javascript" src="js/chrome_ex_oauth.js"></script>
    <script type="text/javascript">

	
		google.load('gdata', '1.x');
		
		var oauth = ChromeExOAuth.initBackgroundPage({
			'request_url': 'https://www.google.com/accounts/OAuthGetRequestToken',
			'authorize_url': 'https://www.google.com/accounts/OAuthAuthorizeToken',
			'access_url': 'https://www.google.com/accounts/OAuthGetAccessToken',
			'consumer_key': 'anonymous',
			'consumer_secret': 'anonymous',
			'scope': 'https://www.google.com/calendar/feeds/',
			'app_name': 'QuickAddCalendar'
		});
	
		function setUIState() {
			if (oauth.hasToken()) {
				chrome.browserAction.setIcon({'path': 'images/icon-on.png'});
			} else {
				chrome.browserAction.setIcon({'path': 'images/icon-off.png'});
			}
		};
		
		function getPopupView() {
			var views = chrome.extension.getViews();
			for (var i = 0; i < views.length; i++) { 
				var view = views[i];
				if (view.location.href == chrome.extension.getURL('popup.html') || chrome.extension.getURL('popup.html') ){ 
					return view;
				} 
			}
		};

		function onAddEvent(xhr, data) {
			//var popup = getPopupView();
			var popup;
			
			var views = chrome.extension.getViews();
			for (var i = 0; i < views.length; i++) { 
				var view = views[i];
				if (view.location.href == chrome.extension.getURL('popup.html') || chrome.extension.getURL('popup.html') ){ 
					popup = view;
				} 
			}
			
			var message = {};
			message.success = true;
			message.xhr = xhr;
			popup.apiNotification(message);
			
		};
 
		function addNewEvent(response) {
			oauth.authorize(function() {
		    	setUIState();
		    	
				var method = 'POST';
				var url = 'https://www.google.com/calendar/feeds/default/private/full';
				var params = {'alt': 'json'};

				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function(data) {
					if (xhr.readyState == 4 && xhr.statusText == "Created") {
				    	onAddEvent(xhr, data);
					} else {
						//console.error(data);
						//console.error(xhr);
					}
				};
				
				var requestBody = constructAtomXML(response);
				
				xhr.open(method, url + '?' + stringify(params), true);
				xhr.setRequestHeader('GData-Version', '1.0');
				xhr.setRequestHeader('Content-Type', 'application/atom+xml');
				xhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
				xhr.send(requestBody);
		  	});
		};
		
		
		function constructAtomXML(response) {
		var strQuickAdd = DBC2SBC(response.quickAdd, true);
			atomXML = ["<?xml version='1.0' encoding='UTF-8'?>",
					"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gCal='http://schemas.google.com/gCal/2005'>",
				  	'<content type="html">', strQuickAdd, '</content>',
				  	'<gCal:quickadd value="true"/>',
					'</entry>'].join('');
		//	}
			
			return atomXML;
		};
		
		
		function injectContentScripts() {
        chrome.windows.getAll({populate:true}, function(windows){
          for (var i = 0; i < windows.length; i++) {
            var tabs = windows[i].tabs;
            for (var j = 0; j < tabs.length; j++) {
              var tab = tabs[j];
              chrome.tabs.executeScript(tab.id,
                                        {file: 'chromeVis_loader.js',
                                         allFrames: true});
            }
          }
        });
      }
		injectContentScripts();
		chrome.contextMenus.create({ "title": "QuickAdd", "contexts": ["selection"], "onclick": addEvent });
		function addEvent() {
			chrome.tabs.getSelected(null, function(tab){
			chrome.tabs.sendRequest(tab.id, {}, function handler(response) {
				});
			});
		}
		chrome.extension.onRequest.addListener(onRequest);
		function onRequest(request, sender, callback) {
			if (request.action == 'selectTxt') {
				if(request.text){
				var strQuickAdd = DBC2SBC(request.text, true);
						atomXML = ["<?xml version='1.0' encoding='UTF-8'?>",
							"<entry xmlns='http://www.w3.org/2005/Atom' xmlns:gCal='http://schemas.google.com/gCal/2005'>",
							'<content type="html">', strQuickAdd, '</content>',
							'<gCal:quickadd value="true"/>',
							'</entry>'].join('');		
							oauth.authorize(function() {
						setUIState();
						
						var method = 'POST';
						var url = 'https://www.google.com/calendar/feeds/default/private/full';
						var params = {'alt': 'json'};

						var xhr = new XMLHttpRequest();
						xhr.onreadystatechange = function(data) {
							if (xhr.readyState == 4 && xhr.statusText == "Created") {
								onAddEvent(xhr, data);
							} else {
								//console.error(data);
								//console.error(xhr);
							}
						};
						
						var requestBody = atomXML;
						
						xhr.open(method, url + '?' + stringify(params), true);
						xhr.setRequestHeader('GData-Version', '1.0');
						xhr.setRequestHeader('Content-Type', 'application/atom+xml');
						xhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
						xhr.send(requestBody);
					});
				
				
				
				
				}      
			}
		};

		function stringify(parameters) {
			var params = [];
		  	for(var p in parameters) {
		    	params.push(encodeURIComponent(p) + '=' + encodeURIComponent(parameters[p]));
		  	}
		  	return params.join('&');
		};
		
		function authenticate() {
			if (!oauth.hasToken()) {
				oauth.authorize(function() {
					setUIState();
				});
			} else {
			}
		};
		
		function getAuthState() {
			return oauth.hasToken();
		}

		function logout() {
			oauth.clearTokens();
			setUIState();
		};
		
		function onGoogleDataLoad() {
			
		};

		setUIState();
		
		google.setOnLoadCallback(onGoogleDataLoad);
		
	</script>
</head>
<body>

</body>
</html>